<template>
  <template v-for="(tag, index) in tags" :key="index">
    <a-tooltip v-if="tag.length > 20" :title="tag">
      <a-tag
        :key="tag"
        closable
        @close="handleClose(tag)"
        @click="handleClick($event, index)"
        :class="{ selected: selectedTag === tag }"
      >
        {{ `${tag.slice(0, 20)}...` }}
      </a-tag>
    </a-tooltip>
    <a-tag
      v-else
      closable
      @close="handleClose(tag)"
      @click="handleClick($event, index)"
      :class="{ selected: selectedTag === tag }"
    >
      {{ tag }}
    </a-tag>
  </template>
  <a-input
    v-if="inputVisible"
    ref="inputRef"
    type="text"
    size="small"
    :style="{ width: '78px' }"
    v-model:value="inputValue"
    @blur="handleInputConfirm"
    @keyup.enter="handleInputConfirm"
  />
  <a-tag v-else @click="showInput" style="border-style: dashed">
    <plus-outlined />
    添加标签
  </a-tag>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs, nextTick } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';

export default defineComponent({
  components: {
    PlusOutlined,
  },
  props: {
    checkableTag: {
      type: Boolean,
      default: false,
    },
    tags: {
      type: Array,
      default: () => [],
    },
  },
  setup(props) {
    const inputRef = ref();
    const state = reactive({
      tags: [],
      selectedTag: '',
      inputVisible: false,
      inputValue: '',
    });

    const handleClose = (removedTag: string) => {
      const tags = state.tags.filter(tag => tag !== removedTag);
      console.log(tags);
      state.tags = tags;
    };

    const showInput = () => {
      state.inputVisible = true;
      nextTick(() => {
        inputRef.value.focus();
      });
    };

    const handleInputConfirm = () => {
      let inputValue: string = state.inputValue;
      let tags: Array<any> = state.tags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      console.log(tags);
      Object.assign(state, {
        tags,
        inputVisible: false,
        inputValue: '',
      });
    };

    const handleClick = (e, index) => {
      if (!props.checkableTag) return;
      console.log(e, index);
      state.selectedTag = state.tags[index];
      console.log(state);
    };
    return {
      ...toRefs(state),
      handleClose,
      showInput,
      handleInputConfirm,
      inputRef,
      handleClick,
    };
  },
});
</script>
<style scoped lang="less">
.ant-tag.selected {
  color: #fff;
  background-color: #1890ff;
  :deep(.anticon-close) {
    color: rgba(255, 255, 255, 1);
  }
}
</style>
